<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline label-width="auto">
      <el-form-item :label="t('dealerAssetManagement.theTitleOfTheProduct')">
        <el-input
          v-model="form.product_name"
          clearable
          :placeholder="t('dealerAssetManagement.theTitleOfTheProduct')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('dealerAssetManagement.productCode')">
        <el-input
          v-model="form.code"
          clearable
          :placeholder="t('dealerAssetManagement.productCode')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('dealerAssetManagement.brand')">
        <el-select
          v-model="form.brand"
          :placeholder="t('dealerAssetManagement.brand')"
          :clearable="true"
          :filterable="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in brandList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('dealerAssetManagement.classification')">
        <el-select
          v-model="form.category"
          :placeholder="t('dealerAssetManagement.classification')"
          :clearable="true"
          :filterable="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in classificationList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('dealerAssetManagement.currency')">
        <el-select
          v-model="form.currency"
          :placeholder="t('dealerAssetManagement.currency')"
          :clearable="true"
          :filterable="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('dealerAssetManagement.dealers')">
        <el-select
          v-model="form.user_id"
          :placeholder="
            t('common.inputText') +
            ' ' +
            t('dealerAssetManagement.dealers') +
            ' ' +
            t('dealerAssetManagement.nameOrEmail')
          "
          :filterable="true"
          :multiple="true"
          :clearable="true"
          :remote="true"
          :remote-method="getCustomerOptions"
          :loading="selectLoading"
          style="width: 250px"
        >
          <el-option
            v-for="item in distributorList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('dealerAssetManagement.warehouse')">
        <el-select
          v-model="form.wid"
          :placeholder="t('dealerAssetManagement.warehouse')"
          :clearable="true"
          :filterable="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('dealerAssetManagement.type')">
        <el-select
          v-model="form.is_futures"
          :placeholder="t('dealerAssetManagement.type')"
          :clearable="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('dealerAssetManagement.arrivalDate')">
        <el-date-picker
          v-model="form.date"
          type="daterange"
          range-separator="-"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          @change="changeTime"
          :editable="false"
          unlink-panels
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">{{
          t('common.search')
        }}</el-button>
        <el-button icon="Refresh" @click="reset">{{ t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleAdd('delivery')">
        {{ t('dealerAssetManagement.delivery') }}
      </el-button>
    </div>
    <!-- 表格主体 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        :label="t('dealerAssetManagement.dealers')"
        prop="user"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('dealerAssetManagement.warehouse')"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(warehouseList, row.wid) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('dealerAssetManagement.type')"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(typeList, row.is_futures) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('dealerAssetManagement.arrivalDate')"
        prop="arrival_date"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('dealerAssetManagement.theTitleOfTheProduct')"
        prop="product_name"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('dealerAssetManagement.productCode')"
        prop="code"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('dealerAssetManagement.brand')"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(brandList, row.brand) }}
        </template>
      </el-table-column>
      <!-- <el-table-column
        :label="t('dealerAssetManagement.computingPower')"
        prop="hashrate"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('dealerAssetManagement.warranty')"
        prop="expiration_date"
        min-width="200"
        :show-overflow-tooltip="true"
      /> -->
      <el-table-column
        :label="t('dealerAssetManagement.pendingQuantity')"
        prop="quantity"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('dealerAssetManagement.theTotalNumberOfOrders')"
        prop="total_qty"
        min-width="200"
        :show-overflow-tooltip="true"
      />
    </el-table>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useEnumeratePicker } from '@/utils'
import { getEnumApi, getDistributorEnumApi, getListApi } from '@/api/order/dealerAssetManagement'
import { getSelectApi as getCustomerSelectApi } from '@/api/customer'

const { t } = useI18n()
const { push } = useRouter()

const multipleSelection = ref<any[]>([])
const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const paginationTotal = ref<number>(0)
const selectLoading = ref<boolean>(false)

const form = ref<Record<string, any>>({
  product_name: '',
  code: '',
  brand: '',
  category: '',
  currency: '',
  user_id: [],
  wid: '',
  is_futures: '',
  date: [],
  start_time: '',
  end_time: '',
  pageIndex: 1,
  pageSize: 20
})

const brandList = ref<Array<Record<string, any>>>([])
const classificationList = ref<Array<Record<string, any>>>([])
const currencyList = ref<Array<Record<string, any>>>([])
const distributorList = ref<Array<Record<string, any>>>([])
const warehouseList = ref<Array<Record<string, any>>>([])
const typeList = ref<Array<Record<string, any>>>([])

// 客户异步下拉框
const getCustomerOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const distributorResp = await getCustomerSelectApi({ role: 'distributor', cusname: value })
    distributorList.value = distributorResp.data
    selectLoading.value = false
  }
}

//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.start_time = dayjs(e[0]).format('YYYY-MM-DD')
    form.value.end_time = dayjs(e[1]).format('YYYY-MM-DD')
  } else {
    form.value.start_time = null
    form.value.end_time = null
  }
}

//点击跳转到发货
const handleAdd = (type: string) => {
  if (multipleSelection.value.length) {
    let isSame = multipleSelection.value.every(
      (item) => item.user_name === multipleSelection.value[0].user_name
    )
    if (!isSame) {
      ElMessage.error('请选择同一经销商')
      return false
    }
    let customer_id = multipleSelection.value[0].user_id
    let cusname = multipleSelection.value[0].user_name
    let productIds = Array.from(
      new Set(multipleSelection.value.map((item) => item.wid + '_' + item.product_id))
    ).join(',')
    console.log('product_id', productIds, customer_id, cusname)
    push({
      path: `/order/dealerAssetManagement/${type}`,
      query: {
        customer_id,
        cusname,
        productIds
      }
    })
  } else {
    push({ path: `/order/dealerAssetManagement/${type}` })
  }
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  brandList.value = resp.data.brand
  classificationList.value = resp.data.category
  currencyList.value = resp.data.currency
  warehouseList.value = resp.data.warehouse
  typeList.value = resp.data.is_futures
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    product_name: '',
    code: '',
    brand: '',
    category: '',
    currency: '',
    user_id: [],
    wid: '',
    is_futures: '',
    date: [],
    start_time: '',
    end_time: '',
    pageIndex: 1,
    pageSize: 20
  }
  paginationTotal.value = 0
  initialize()
}
//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
  console.log('multipleSelection', multipleSelection.value)
}
onMounted(() => {
  getDropDownBoxInfo()
})
onActivated(() => {
  initialize()
})
</script>

<style lang="less" scoped></style>
